#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <pthread.h>
#include <string.h>
#include "errno.h"
#include"busMq.h"

typedef struct msgbuf_t {
        long mtype;       /* message type, must be > 0 */
        int source_addr;
        BUSMQ_MSG_t msg;
}msgbuf_t;


void *thr_BUSMQ_recive(void *arg)
{
    BUSMQ_Control_t* control = (BUSMQ_Control_t*)arg;
    msgbuf_t msg = {0};
    control->run = 1;
	while(control->run)
	{   
        if(control->busid > 0 && control->recivecall)
        {
            memset(&msg,0,sizeof(msg));
       		if(0 < msgrcv(control->busid,&msg,sizeof(msg)-sizeof(long),control->addr,IPC_NOWAIT))
            {
                if(control->recivecall)
                    control->recivecall(&msg.msg,msg.source_addr);
            }     
        }
        usleep(50000);
	}
    return (void*)0;
}


int BUSMQ_MSG_send(BUSMQ_Control_t* control,BUSMQ_MSG_t*my_msg,int addr)
{
    int ret = 0;
    if(control->busid <= 0)
        return -1;
    msgbuf_t msg = {0};
    msg.mtype = addr;
    memcpy(&msg.msg,my_msg,sizeof(BUSMQ_MSG_t));
     msg.source_addr = control->addr;
    ret = msgsnd(control->busid, &msg,msg.msg.datalen+sizeof(int)+sizeof(int), 0);
   // printf("PPMQ_MSG_send ret:%d errno:%d\n",ret,errno);
    return ret;
}


int BUSMQ_CREATE(int key_id,BUSMQ_Control_t *control,BUSMQ_RECIVE_CAMMBACK msg_call,int addr,int main)
{
    int ret = 0;
    pthread_t thr_pid = 0;
    int busid = 0;
    if(main)
        busid = msgget(key_id,IPC_CREAT|0666 );
    else
        busid = msgget(key_id,0666 );
	if(0 > busid)
	{
		printf("msgget faile\n");
		return -1;
	}
    control->busid = busid;
    control->recivecall = msg_call;
    control->addr = addr;
    //注册线程
    ret = pthread_create(&thr_pid,NULL, thr_BUSMQ_recive,control);
    if(ret !=0 )
    {
        printf("thread create faile ret = %d",ret);
        return -1;
    }
    printf("PPMQ_CREATE success\n");
    return 1;
}

int BUSMQ_DESTROY_NODE(BUSMQ_Control_t* control)
{

    //销毁本节点
    if(control->busid <= 0)
        return -1;
    control->recivecall = NULL;
    control->run = 0;
    return 0;
}

int BUSMQ_DESTROY_BUS(BUSMQ_Control_t* control)
{
    //销毁本节点
    if(control->busid <= 0)
        return -1;
    control->recivecall = NULL;
    control->run = 0;
    return msgctl(control->busid, IPC_RMID, NULL);
}





